<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{common/header :: commonHead}"></head>
<META HTTP-EQUIV="Cache-Control" CONTENT="no-cache, must-revalidate">
<body class="gray-bg">
<div class="wrapper wrapper-content animated fadeInRight">
    <div class="row">
        <div class="col-sm-12">
            <div class="ibox float-e-margins">
                <div class="ibox-title">
                    <h5>规则列表</h5>
                    <div class="ibox-tools">
                        <a href="/userLabel/form?type=add" title="添加"><i class="glyphicon glyphicon-plus-sign"></i></a>
                        <a href="javascript: window.location.href='/userLabel/list';" title="刷新"><i
                                class="glyphicon glyphicon-repeat"></i></a>
                    </div>
                </div>
                <div class="ibox-content">
                    <div class="row">
                        <form id="search-form" class="form-inline">
                            <div class="col-sm-8">
                                <div class="input-group col-sm-4">
                                    <input type="text" name="keyword" placeholder="请输名称"
                                           class="input-sm form-control search-input">
                                    <span class="input-group-btn">
                                        <button type="button" class="btn btn-sm btn-primary submit-search"> 搜索</button>
                                    </span>
                                </div>
                            </div>
                        </form>
                    </div>
                    <div class="row">
                        <div class="col-sm-12">
                            <div id="label-group-table"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="modal fade in" id="ticketModel" tabindex="-1" role="dialog" aria-labelledby="myModalLabel"
     aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content" style="width: 500px">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
                <h4 class="modal-title" id="ticketModelLabel"></h4>
            </div>
            <div class="modal-body" style="height: 300px">
                <div class="input-group">
                    <input value="" type="text" placeholder="输入关键词" class="input-sm form-control" id="search-ticket">
                    <span class="input-group-btn">
                        <button type="button" class="btn btn-sm btn-primary" id="search-ticket-btn"> 搜索</button>
                    </span>
                </div>
                <table class="table">
                    <thead style="display:table;width:100%;table-layout:fixed;">
                    <tr>
                        <th style="width: 20%;">LOGO</th>
                        <th style="width: 35%;">券名称</th>
                        <th style="width: 10%;">总量</th>
                        <th style="width: 15%;">类型</th>
                        <th style="width: 20%;">操作</th>
                    </tr>
                    </thead>
                    <tbody style="display:block;height:200px;overflow-y:auto;width: 100%;text-align: center" id="inner">

                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
</body>
<script src="/layui/layui.js"></script>
<script th:inline="javascript">
    let keyword, table, belonging = [[${sysUser.id}]], groupId, nodes = new Map(), node = (e, b) => {
        return {e: e, b: b}
    };
    loadTable();

    function loadTable() {
        layui.use('table', function () {
            table = layui.table;
            table.render({
                id: 'label-group-table',
                elem: '#label-group-table',
                height: 600,
                url: ipDomain + '/quanquan-user/labelGroup/list',
                contentType: 'application/json; charset=utf-8',
                loading: true,
                skin: 'line',
                size: 'sm',
                parseData: function (res) { //res 即为原始返回的数据
                    return {
                        "code": res.resCode, //解析接口状态
                        "msg": res.resMsg, //解析提示文本
                        "count": res.data.total, //解析数据长度
                        "data": res.data.list //解析数据列表
                    };
                },
                method: 'post',
                limits: [10, 20, 40, 100],
                request: {
                    pageName: 'page',
                    limitName: 'size'
                },
                where: {belonging: belonging},
                page: true,
                cellMinWidth: 80,
                cols: [[
                    {field: 'id', title: 'ID', hide: true, sort: true, fixed: 'left'},
                    {
                        field: 'name', title: '名称', fixed: 'left', sort: true, templet: (e) => {
                            return e.name.replace(keyword, '<span style="color: red">' + keyword + '</span>')
                        }
                    },
                    {field: 'author', title: '作者', sort: true,  fixed: 'left'},
                    {field: 'scene', title: '使用场景', sort: true,  fixed: 'left'},
                    {field: 'containsNum', title: '包含人数', sort: true,  fixed: 'left'},
                    {field: 'createTime', title: '创建时间', sort: true,  fixed: 'left'},
                    {field: 'updateTime', title: '编辑时间', sort: true,  fixed: 'left'},
                    {
                        field: 'pushStatus',
                        title: '推送进度', fixed: 'left', templet: function (e) {
                            let temp = '';
                            if (e.pushStatus == 0) {
                                temp = '未推送';
                            } else if (e.pushStatus == 1) {
                                let s = e.pushSuccess;
                                let f = e.pushFailed;
                                temp = '成功' + s + ' / 失败' + f;
                            } else if (e.pushStatus == 2) {
                                temp = '<span style="color: red">推送失败</span>'
                            }
                            return temp
                        }
                    },
                    {field: 'lastPushTime', title: '推送时间', sort: true,  fixed: 'left'},
                    {field: 'lastSyncTime', title: '同步时间',  fixed: 'left'},
                    {
                        title: '操作', width: 400, templet: function (e) {
                            return '<button class="layui-btn layui-btn-xs" onclick="edit(\'' + e.id + '\')">编辑</button> '
                                + '<button onclick="ticketPush(\'' + e.id + '\')" ' +
                                'data-toggle="modal" data-target="#ticketModel" class="layui-btn layui-btn-normal layui-btn-xs modal-trigger">操作</button> '
                                + '<button onclick="asyncLabel($(this),\'' + e.id + '\')" class="layui-btn layui-btn-xs">同步</button>'
                                + '<button onclick="synRecord(\'' + e.id + '\')" class="layui-btn layui-btn-xs">同步历史</button>'
                                + '<button onclick="remove(\'' + e.id + '\')" class="layui-btn layui-btn-danger layui-btn-xs">删除</button> '
                                // + '<button onclick="viewDetails(\'' + e.id + '\')" class="btn btn-xs btn-primary">查看</button> '
                                ;

                        }, fixed: 'left'
                    }
                ]],
                done: function (res, curr, count) {
                    this.where = {
                        keyword: keyword,
                        belonging: belonging
                    };
                    $(function () {
                        let hoverTimer;
                        $('.layui-table-box table tr [data-field="name"]').hover(function (e) {
                            hoverTimer = window.setTimeout(function () {
                                let _this = $(e.currentTarget);
                                let id = _this.parent().find('[data-field="id"]').find('div').html();
                                let data = getFullLabel(id);
                                let tmp = '名称：' + data.name + '<br>'
                                    + '包含人数：' + data.containsNum + '<br>'
                                    + '标签：' + data.labels + '<br>'
                                ;
                                layer.tips(tmp, _this, {tips: [3,'rgba(0, 0, 0, 0.5)']});
                            }, 1000);
                        }, function () {
                            clearTimeout(hoverTimer);
                        });
                    });
                }
            });
        });
    }

    function asyncLabel(btn, id) {
        let find = btn.parent().parent().parent().find('[data-field="containsNum"]').find('div');
        // btn.button('loading');
        btn.attr('disabled');
        btn.addClass('layui-btn-disabled');
        $.get(ipDomain + '/quanquan-user/labelGroup/sync/' + id, (res) => {
            if (res.resCode == 0) {
                find.html('<img style="height: 14px" src="/layuiuse/css/modules/layer/default/loading-2.gif">');
                setTimeout(function () {
                    resetData(find, btn, id);
                }, 1000);
            } else {
                layer.msg(res.resMsg, {icon: 11, time: 500, shade: [0.5, '#000', true]});
            }
        });
    }

    function viewDetails(id) {

    }

    function resetData(e, b, id) {
        $.get(ipDomain + '/quanquan-user/labelGroup/get', {id: id}, (res) => {
            if (res.resCode == 0) {
                if (res.data.synStatus == 2) {
                    e.html(res.data.containsNum);
                    // b.button('reset');
                    b.removeAttr('disabled');
                    b.removeClass('layui-btn-disabled');
                } else if (res.data.synStatus == 1) {
                    setTimeout(function () {
                        resetData(e, b, id);
                    }, 500);
                } else {
                    layer.msg('同步失败', {icon: 11, time: 500, shade: [0.5, '#000', true]});
                }
            } else {
                layer.msg(res.resMsg, {icon: 11, time: 500, shade: [0.5, '#000', true]});
            }
        });
    }

    function remove(id) {
        if (id == null) {
            layer.msg('Id不能为空', {icon: 11, time: 1000, shade: [0.5, '#000', true]});
        }
        $.get(ipDomain + '/quanquan-user/labelGroup/remove/' + id,
            (res) => {
                if (res.resCode == 0) {
                    layer.msg('删除成功', {icon: 1, time: 500, shade: [0.5, '#000', true]});
                    reloadTable();
                } else {
                    layer.msg(res.resMsg, {icon: 11, time: 1000, shade: [0.5, '#000', true]});
                }
            }
        );
    }

    function edit(id) {
        window.location.href = '/userLabel/form?type=edit&id=' + id;
    }
    function synRecord(id) {
        window.location.href = '/userLabel/syn_record?id=' + id;
    }

    $(".submit-search").click(function () {
        reloadTable();
    });

    function reloadTable() {
        let queryData = $('#search-form').serializeJson2Obj();
        keyword = queryData.keyword;
        table.reload(
            'label-group-table',
            {
                page: {
                    curr: 1
                },
                where: {
                    keyword: keyword,
                    belonging: belonging
                }
            }
        );
    }

    function ticketPush(id) {

        window.location.href = '/userLabel/operate?id=' + id;

        // groupId = id;
        // nodes.set(id, node(e, false));
        // $("#ticketModelLabel").html("券推送到：" + name);
        // setData(id);
    }

    function setData(id) {
        $("#inner").html('<div id="loading-box" style="padding-top: 50px"><img src="/layuiuse/css/modules/layer/default/loading-0.gif"></div>');
        let _this = $("#search-ticket");
        let keyword = _this.val();
        $.ajax({
            url: "/coupon/search?keyword=" + keyword + "&activeId=",
            type: "get",
            success: function (res) {
                let list = res.data.list;
                let str = '';
                if (list != null) {
                    list.forEach(obj => {
                        str += '<tr style="display:table;width:100%;table-layout:fixed;">' +
                            '<td style="display:none;">' + obj.id + '</td>' +
                            '<td style="width: 20%"><img style="height: 40px" src="' + obj.image + '" ' +
                            'onerror="this.src=\'/img/default_coup.png\'"></td>' +
                            '<td style="width: 35%">' + obj.name + '</td>' +
                            '<td style="width: 10%">' + (obj.sumTatal == null ? '∞' : obj.remainTotal) + '</td>' +
                            '<td style="width: 15%">' + (obj.type == 1 ? '优惠券' : '停车券') + '</td>' +
                            '<td style="width: 20%"><a type="button" onclick="pushCoupon(\'' + obj.id + '\')" ' +
                            'class="btn btn-primary btn-xs">推送</a></td></tr>'
                    });
                } else {
                    str = '<div style="padding-top: 50px">暂无内容</div>'
                }
                $('#loading-box').remove()
                $("#inner").html(str);
            }
        });
    }

    $("#search-ticket-btn").click(function () {
        setData(groupId);
    });
    $("#search-ticket").on("keydown", function (e) {
        if (e.keyCode != 13) {
            return;
        }
        setData(groupId);
    });

    let adminId = [[${sysUser.id}]];
    let adminName = [[${sysUser.username}]];

    function pushCoupon(coupId) {
        let num = prompt("请输入优惠券数量", "1");
        if (null == num) {
            return;
        }
        if (isNaN(num)) {
            layer.msg('请输入正确的数字', {icon: 15, time: 1000, shade: [0.5, '#000', true]});
        }
        let postData = {
            labelGroupId: groupId,
            couponId: coupId,
            couponNum: num,
            adminId: adminId,
            adminName: adminName
        };
        $.ajax({
            url: ipDomain + "/quanquan-user/labelGroup/push",
            data: JSON.stringify(postData),
            contentType: 'application/json',
            type: "POST",
            async: false,
            success: function (data) {
                let code = data.resCode;
                if (code == 0) {
                    $("#ticketModel").modal('hide');
                    console.log(nodes)
                    showProgress()
                } else {
                    layer.alert(data.resMsg);
                }
            }
        });
    }

    function showProgress() {
        if (nodes.size > 0) {
            nodes.forEach((v, k) => {
                $.ajax({
                    url: ipDomain + '/quanquan-user/labelGroup/pushStatus',
                    data: {id: k},
                    type: 'GET',
                    async: false,
                    success: (res) => {
                        let s = res.data.success;
                        let f = res.data.failed;
                        let t = res.data.total;
                        let ps = 100;
                        let pf = 0;
                        if (null != s, f, t && t != 0) {
                            ps = s / t * 100;
                            pf = f / t * 100;
                        }
                        let container = v.e.parent().parent().parent().find('[data-field="pushStatus"]').find('div');
                        let temp = '<div class="progress progress-striped active progress-small">' +
                            '<div style="width: ' + ps + '%" class="progress-bar progress-bar-success"></div>' +
                            '<div style="width: ' + pf + '%" class="progress-bar progress-bar-danger"></div></div>'
                        if (res.data.pushStatus == 1) {
                            container.html(temp);
                            if (v.b) {
                                container.html('成功' + s + ' / 失败' + f);
                                setPushTime(k, v.e.parent().parent().parent().find('[data-field="lastPushTime"]').find('div'));
                                nodes.delete(k);
                            } else {
                                nodes.set(k, node(v.e, true));
                            }
                        } else if (res.data.pushStatus == 2) {
                            container.html('<span style="color: red">推送失败</span>');
                            nodes.set(k, node(v.e, true));
                        } else if (res.data.pushStatus == 3) {
                            container.html(temp);
                        }
                    }
                });
            });
            setTimeout(showProgress, 500);
        }
    }

    function setPushTime(i, e) {
        $.get(ipDomain + '/quanquan-user/labelGroup/get', {id: i}, (res) => {
            e.html(res.data.lastPushTime)
        })
    }

    function getFullLabel(id) {
        let res = {}
        $.ajax({
            url: ipDomain + '/quanquan-user/labelGroup/get/' + id,
            type: 'GET',
            async: false,
            success: (result) => {
                res = result.data;
            }
        })
        return res;
    }

</script>
</html>